﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Forms;
using System.Collections.ObjectModel;
using MicroFractal.iTunesBrowser.Core;
using MicroFractal.iTunesBrowser.Business;
using System.Windows.Interop;
using System.Drawing;
using MicroFractal.iTunesBrowser.Cultures;
using System.Globalization;
using MicroFractal.iTunesBrowser.Core.Device;
using System.ComponentModel;
using System.Windows.Controls.Primitives;

namespace MicroFractal.iTunesBrowser
{
    /// <summary>
    /// Interaction logic for FrmMain.xaml
    /// </summary>
    public partial class FrmMain : Window
    {
        public FrmMain()
        {
            try
            {
                CultureResources.ResourceProvider.DataChanged += new EventHandler(ResourceProvider_DataChanged);
                CultureResources.ChangeCulture(Properties.Settings.Default.DefaultCulture);

                InitializeComponent();
                //DeviceManager.Instance.Devices.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(Devices_CollectionChanged);
                //lstCovers.ItemsSource = new CoverList();

                lstDevices.ItemsSource = DeviceManager.Instance.Devices;

                _songs.GroupDescriptions.Add(new PropertyGroupDescription("Album"));
                _songs.Source = new ObservableCollection<Song>();
                lstSongs.ItemsSource = _songs.View;

                using (System.Windows.Forms.FolderBrowserDialog f = new System.Windows.Forms.FolderBrowserDialog())
                {
                    if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        DeviceManager.Instance.CreateFolderDevice(f.SelectedPath);
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        BitmapSource imgCD = Imaging.CreateBitmapSourceFromHBitmap(Properties.Resources.CD.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());

        void ResourceProvider_DataChanged(object sender, EventArgs e)
        {

        }

        IDevice _currentDevice;
        CollectionViewSource _songs = new CollectionViewSource();

        private void lstSongs_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            GridView view = (GridView)lstSongs.View;

            double i = 0;
            foreach (GridViewColumn c in view.Columns)
                i += c.ActualWidth;

            i -= colName.ActualWidth;

            if (lstSongs.ActualWidth - i >= 30)
                colName.Width = lstSongs.ActualWidth - i - 30;
        }

        #region  Menu Events

        private void menuExit_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        #endregion

        private void myImage_Loaded(object sender, RoutedEventArgs e)
        {
            if (((System.Windows.Controls.Image)sender).Source == null)
            {
                ((System.Windows.Controls.Image)sender).Source = imgCD;
            }
        }

        void m_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Controls.MenuItem m = (System.Windows.Controls.MenuItem)sender;

            if (Properties.Resources.Culture != null && !Properties.Resources.Culture.Equals(m.Tag))
            {
                CultureResources.ChangeCulture((CultureInfo)m.Tag);

                foreach (System.Windows.Controls.MenuItem mm in ((System.Windows.Controls.MenuItem)m.Parent).Items)
                    mm.IsChecked = false;

                m.IsChecked = true;
            }
        }

        private void menuLanguage_Initialized(object sender, EventArgs e)
        {
            foreach (CultureInfo c in CultureResources.SupportedCultures)
            {
                System.Windows.Controls.MenuItem m = new System.Windows.Controls.MenuItem();
                m.Header = c.DisplayName;
                m.Tag = c;
                m.Click += new RoutedEventHandler(m_Click);
                if (Properties.Resources.Culture != null && Properties.Resources.Culture.Equals(c))
                    m.IsChecked = true;
                menuLanguage.Items.Add(m);
            }
        }

        private void menuFile_SourceUpdated(object sender, DataTransferEventArgs e)
        {

        }

        private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            if (_currentDevice != null)
                e.CanExecute = _currentDevice.Status == DeviceStatusEnum.Available;
            else
                e.CanExecute = true;
        }

        private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            using (FolderBrowserDialog f = new FolderBrowserDialog())
            {
                if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    List<IDownloadableObject> l = new List<IDownloadableObject>();
                    if (e.Parameter.ToString() == "Albums")
                    {
                        l.AddRange((IEnumerable<IDownloadableObject>)lstCovers.SelectedItems.Cast<IDownloadableObject>());
                    }
                    else
                    {
                        l.AddRange((IEnumerable<IDownloadableObject>)lstSongs.SelectedItems.Cast<IDownloadableObject>());
                    }

                    FrmDownloadProgress dp = new FrmDownloadProgress();
                    dp.StartDownload(_currentDevice, l, f.SelectedPath);//TODO get the Create Tree from configuration
                }
            }
        }

        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {

        }

        private void lstCovers_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //TODO change this method to support other types of data
            foreach (Album a in e.AddedItems)
                foreach (Song s in a.Songs)
                    ((ObservableCollection<Song>)_songs.Source).Add(s);
            foreach (Album a in e.RemovedItems)
                foreach (Song s in a.Songs)
                    ((ObservableCollection<Song>)_songs.Source).Remove(s);
        }

        private void ChangeSelectedItemsBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
        }
        private void ChangeSelectedItemsBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            if (e.Parameter.ToString() == "All")
            {
                ((System.Windows.Controls.ListBox)e.Source).SelectAll();
            }
            else
            {
                ((System.Windows.Controls.ListBox)e.Source).UnselectAll();
            }
        }

        private void lstDevices_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            _currentDevice = (IDevice)lstDevices.SelectedItem;

            Cursor = System.Windows.Input.Cursors.Wait;

            if (_currentDevice != null)
                BindData(_currentView);
            //lstCovers.ItemsSource = LibraryManager.GetLibrary(_currentDevice, true).Albums;

            Cursor = System.Windows.Input.Cursors.Arrow;
        }

        private void SelectToggleButton()
        {
            cmdAlbums.IsChecked = _currentView == View.Albumns;
            cmdPlaylists.IsChecked = _currentView == View.Playlist;
            cmdSongs.IsChecked = _currentView == View.Songs;
            cmdArtists.IsChecked = _currentView == View.Artists;
        }

        private View _currentView;
        private void SelectView(View view)
        {
            if (_currentView != view)
            {
                _currentView = view;

                BindData(_currentView);
            }

            SelectToggleButton();
        }

        private void BindData(View view)
        {
            switch (view)
            {
                case View.Albumns:
                    this.lstCovers.ItemsSource = LibraryManager.GetLibrary(_currentDevice, false).Albums;
                    break;
                case View.Artists:
                    this.lstCovers.ItemsSource = LibraryManager.GetLibrary(_currentDevice, false).Artists;
                    break;
                case View.Playlist:
                    this.lstCovers.ItemsSource = LibraryManager.GetLibrary(_currentDevice, false).Playlists;
                    break;
                case View.Songs:
                    this.lstCovers.ItemsSource = LibraryManager.GetLibrary(_currentDevice, false).Songs;
                    break;
            }
        }

        public enum View { Albumns, Artists, Playlist, Songs }

        private void cmdSongs_Click(object sender, RoutedEventArgs e)
        {
            SelectView(View.Songs);
        }

        private void cmdArtists_Click(object sender, RoutedEventArgs e)
        {
            SelectView(View.Artists);
        }

        private void cmdAlbums_Click(object sender, RoutedEventArgs e)
        {
            SelectView(View.Albumns);
        }

        private void cmdPlaylists_Click(object sender, RoutedEventArgs e)
        {
            SelectView(View.Playlist);
        }
    }
}
